#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;

pub fn exec_cmd_silent(exe: &str, cmd: &str) -> Option<String> {
    exec_cmd(exe, cmd, true)
}

pub fn exec_cmd(exe: &str, cmd: &str, is_silent: bool) -> Option<String> {
    #[cfg(target_os = "windows")]
    let command_str = format!("{} {}", exe, cmd);

    #[cfg(target_os = "macos")]
    let command_str = format!("./{} {}", exe, cmd);

    if !is_silent {
        println!("Info[launcher] : command_str = {}", &command_str);
    }

    let test = std::thread::spawn(move || {
        let cur_path = std::env::current_exe().unwrap();
        let cur_path = cur_path.parent().unwrap().to_str().unwrap();

        #[cfg(target_os = "windows")]
        {
            std::process::Command::new("cmd")
                .current_dir(cur_path)
                .raw_arg("/C")
                .raw_arg(&command_str)
                .output()
                .expect("command failed to start")
        }

        #[cfg(target_os = "macos")]
        {
            let command_str = format!("./{}", &command_str);
            std::process::Command::new("sh")
                .current_dir(cur_path)
                .arg("-c")
                .arg(&command_str)
                .output()
                .expect("command failed to start")
        }
    });

    let Ok(output) = test.join() else {
        return None;
    };

    if let Ok(stderr) = String::from_utf8(output.stderr) {
        if !stderr.is_empty() {
            println!("Error[launcher] : stderr = {}", stderr.trim());
        }
    };

    let Ok(stdout) = String::from_utf8(output.stdout) else {
        println!("Error[launcher] : String::from_utf8(output.stdout)");
        return None;
    };

    if !stdout.is_empty() {
        //println!("Info[launcher] : stdout ({} {}) = \n{}", &exe, &cmd, &stdout.trim().to_string());
        println!("=== {} {} ===\n{}", &exe, &cmd, &stdout.trim().to_string());
    }

    Some(stdout.trim().to_string())
}
